const models = require('../db/mysqldb/index')
const logger = require('../utils/logger')

class ChatGroupUserRelationModel {
  /**
   * @description 加群
   * @param {string} userId
   * @returns
   */
  static async join (user_id, group_id, user_alias) {
    return await models.chat_group_user_relation.create({
      group_id,
      user_id,
      user_alias
    })
  }

  /**
   * @description 退群
   * @param {string} userId
   * @returns
   */
  static async exit (user_id, group_id) {
    return await models.chat_group_user_relation.update(
      {
        delete_timestamp: Date.now(),
      },
      {
        where: { group_id, user_id },
      }
    )
  }

  /**
   * @description 查找人员信息
   * @param {string} userId
   * @returns
   */
  static async findMemberId (group_id) {
    const sql = `select user_id from chat_group_user_relation where group_id = ${group_id} and delete_timestamp is NULL`
    logger.info(`ChatGroupUserRelationModel`, `findMemberId`, `sql`, sql)
    const result = await models.sequelize.query(sql, {
      replacements: ['active'],
      type: models.sequelize.QueryTypes.SELECT,
    })
    return result
  }

  /**
   * @description 查找人员信息
   * @param {string} userId
   * @returns
   */
  static async findMemberInfo (group_id) {
    const sql = `select cgur.user_id,su.realname,su.avatar,su.status from chat_group_user_relation cgur inner join sys_user su on cgur.user_id = su.user_id where cgur.group_id = ${group_id} and cgur.delete_timestamp is NULL and su.delete_timestamp is NULL`
    logger.info(`ChatGroupUserRelationModel`, `findMemberInfo`, `sql`, sql)
    const result = await models.sequelize.query(sql, {
      replacements: ['active'],
      type: models.sequelize.QueryTypes.SELECT,
    })
    return result
  }

  /**
   * @description 查找人员信息 通过用户id
   * @param {string} userId
   * @returns
   */
  static async findMemberByUserId (group_id, user_id) {
    const sql = `select user_id from chat_group_user_relation where group_id = ${group_id} and user_id = ${user_id} and delete_timestamp is NULL`
    const result = await models.sequelize.query(sql, {
      replacements: ['active'],
      type: models.sequelize.QueryTypes.SELECT,
    })
    return result
  }

  /**
   * @description 查找当前用户群组列表
   * @param {string} userId
   * @returns
   */
  static async findByUserId (user_id) {
    const sql = `
      select a.group_id,
      a.group_name,
      a.group_notice,
      a.group_avatar,count(1) userNUm from chat_group_info a left join chat_group_user_relation b on a.group_id=b.group_id
      where a.group_id in (select group_id from chat_group_user_relation where user_id=${user_id})
      group by  
      a.group_id,
      a.group_name,
      a.group_notice,
      a.group_avatar`
    const result = await models.sequelize.query(sql, {
      replacements: ['active'],
      type: models.sequelize.QueryTypes.SELECT,
    })
    return result
  }

}
module.exports = {
  ChatGroupUserRelationModel,
}
